package com.yy.wga.mp.module.goods.task;

import com.yy.wga.mp.module.goods.entity.bo.GoodsIdBO;
import com.yy.wga.mp.module.goods.manager.ProductManager;
import com.yy.wga.mp.module.goods.service.GoodsHeadSupplierInfoService;
import com.yy.wga.common.core.aop.DistributedLock;
import com.yy.wga.mp.common.interceptor.RequestUserHolder;
import com.yy.wga.mp.common.utils.common.StringUtils;
import com.yy.wga.mp.module.goods.api.request.product.GetHeadSupplierProductListReq;
import com.yy.wga.mp.module.goods.api.response.product.GetHeadSupplierProductDetailDTO;
import com.yy.wga.mp.module.goods.api.response.product.GetHeadSupplierProductListDTO;
import com.yy.wga.mp.module.merchant.entity.pojo.MerchantInfoDO;
import com.yy.wga.mp.module.merchant.service.MerchantInfoService;
import com.yy.wga.mp.module.promoter.service.IProductService;
import com.yy.wga.mp.module.resource.entity.pojo.ResourceGoodsCategoryExtendDO;
import com.yy.wga.mp.module.resource.service.ResourceGoodsCategoryExtendService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class SyncHeadSupplierGoodsTask {

    @Resource
    private ProductManager productManager;
    @Resource
    private IProductService productService;
    @Resource
    private GoodsHeadSupplierInfoService goodsHeadSupplierInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private ResourceGoodsCategoryExtendService resourceGoodsCategoryExtendService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0 */2 * * ?")
    @DistributedLock(value = "'syncHeadSupplierGoods'")
    public void syncHeadSupplierGoods() {
        List<MerchantInfoDO> merchantInfoDOList = merchantInfoService.list();
        for (MerchantInfoDO merchantInfoDO : merchantInfoDOList) {
            String appKey = merchantInfoDO.getAppKey();
            BaseRequestDTO baseRequestDTO = new BaseRequestDTO();
            baseRequestDTO.setAppKey(appKey);
            RequestUserHolder.setBaseRequest(baseRequestDTO);

            Boolean hasMore = false;
            String nextKey = null;

            GetHeadSupplierProductListReq getHeadSupplierProductListReq = new GetHeadSupplierProductListReq();
            getHeadSupplierProductListReq.setPageSize(10);
//            double score = 0d;
//            Set<DefaultTypedTuple<String>> typedTupleList = new LinkedHashSet<>();
            List<GoodsIdBO> syncGoodsIdBOList = new ArrayList<>();
            do {
                if (StringUtils.isNotBlank(nextKey)) {
                    getHeadSupplierProductListReq.setNextKey(nextKey);
                }
                try {
                    GetHeadSupplierProductListDTO headSupplierProductList = productService.getHeadSupplierProductList(getHeadSupplierProductListReq);
                    hasMore = headSupplierProductList.getHasMore();
                    nextKey = headSupplierProductList.getNextKey();

                    List<GetHeadSupplierProductListDTO.Product> list = headSupplierProductList.getList();

                    // 查询每个商品
                    for (GetHeadSupplierProductListDTO.Product product : Optional.ofNullable(list).orElse(new ArrayList<>())) {
                        // 同步商品
                        GoodsIdBO goodsIdBO = new GoodsIdBO();
                        goodsIdBO.setProductId(product.getProductId());
                        goodsIdBO.setShopAppid(product.getAppid());
                        // 同步合作商品
                        boolean syncFlag = productManager.syncHeadSupplierProductDetail(goodsIdBO);
                        if (syncFlag) {
                            boolean syncToDb = goodsHeadSupplierInfoService.syncInfoToDb(goodsIdBO);
                            if (syncToDb) {
                                syncGoodsIdBOList.add(goodsIdBO);
                            }
//                            DefaultTypedTuple<String> defaultTypedTuple = new DefaultTypedTuple<>(JsonUtils.toJSONString(goodsIdBO), score++);
//                            typedTupleList.add(defaultTypedTuple);
                        }
                    }
                } catch (Exception e) {
                    log.error("同步合作商品失败。", e);
                    break;
                }
            } while (hasMore);

            goodsHeadSupplierInfoService.sync(syncGoodsIdBOList);


//            stringRedisTemplate.executePipelined(new SessionCallback<Objects>() {
//                @Override
//                public Objects execute(RedisOperations operations) throws DataAccessException {
//                    // 有限存储临时空间
//                    String headSupplierGoodsListTempKey = RedisConstants.getHeadSupplierGoodsListTempKey(appKey);
//                    operations.opsForZSet().add(headSupplierGoodsListTempKey, typedTupleList);
//                    operations.expire(headSupplierGoodsListTempKey, 1, TimeUnit.DAYS);
//                    // 删除原空间数据
//                    String headSupplierGoodsListKey = RedisConstants.getHeadSupplierGoodsListKey(appKey);
//                    operations.delete(headSupplierGoodsListKey);
//                    // 临时key更名
//                    operations.renameIfAbsent(headSupplierGoodsListTempKey, headSupplierGoodsListKey);
//                    operations.expire(headSupplierGoodsListKey, 1, TimeUnit.DAYS);
//                    return null;
//                }
//            });


            RequestUserHolder.setBaseRequest(null);
        }
    }

    public void HeadSupplierGoodsToDb(GetHeadSupplierProductDetailDTO.Product product) {

    }


    //    @Scheduled(cron = "0 0/10 * * * ? ")
    public void syncChooseHeadSupplierGoods() {
        List<MerchantInfoDO> merchantInfoDOList = merchantInfoService.list();
        for (MerchantInfoDO merchantInfoDO : merchantInfoDOList) {
            String appKey = merchantInfoDO.getAppKey();
            BaseRequestDTO baseRequestDTO = new BaseRequestDTO();
            baseRequestDTO.setAppKey(appKey);
            RequestUserHolder.setBaseRequest(baseRequestDTO);

            GetHeadSupplierProductListReq getHeadSupplierProductListReq = new GetHeadSupplierProductListReq();
            getHeadSupplierProductListReq.setPageSize(10);
            List<ResourceGoodsCategoryExtendDO> extendList = resourceGoodsCategoryExtendService.getResourceGoodsCategoryExtendList(appKey);
            // 按spuId shopAppid 去重
            List<ResourceGoodsCategoryExtendDO> deduplicatedList = new ArrayList<>(extendList.stream().collect(Collectors.toMap(e -> e.getSpuId() + "-" + e.getShopAppid(), e -> e, (existing, replacement) -> existing)).values());

            // 查询每个商品
            for (ResourceGoodsCategoryExtendDO extend : deduplicatedList) {
                // 同步商品
                GoodsIdBO goodsIdBO = new GoodsIdBO();
                goodsIdBO.setProductId(extend.getSpuId());
                goodsIdBO.setShopAppid(extend.getShopAppid());
                // 同步合作商品
                productManager.syncHeadSupplierProductDetail(goodsIdBO);
            }
            RequestUserHolder.setBaseRequest(null);
        }
    }
}